/**
 * Course			:	ISYS2119 - BIS Development 2
 * Assignment		:	02
 * Date due			:	01/08/2012
 * Program 			:	Saigon Bike Rental Catalogue System
 * 
 * Programmer		:	Vuu Ngoc My Linh, Tran Thi Van Anh
 * StudentID     	:	s3342015, s3342025
 * Attributions		:	Lecture slides, Blackboard, Tutorials, Websites
 * ====================================================================
 * Description: Functions of buttons on the forms 						
 */

package rmit.ISYS2119.assign02;

import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class ButtonFunctionality {

	private static BufferedWriter bufferedWriter;

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}

	public static void first(FormBikeCatalogue form) {

		FormBikeCatalogue.loadBike(0);
	}

	public static void previous(FormBikeCatalogue form) {
		int index = form.currentIndex - 1;
		if (index < 0) {
			form.currentIndex = FormBikeCatalogue.bikesList.size() - 1;
		} else {
			form.currentIndex -= 1;

		}
		FormBikeCatalogue.loadBike(form.currentIndex);
	}

	public static void next(FormBikeCatalogue form) {
		int index = form.currentIndex + 1;
		if (index == FormBikeCatalogue.bikesList.size()) {
			form.currentIndex = 0;
		} else {
			form.currentIndex += 1;
		}
		FormBikeCatalogue.loadBike(form.currentIndex);
	}

	public static void last(FormBikeCatalogue form) {
		FormBikeCatalogue.loadBike(FormBikeCatalogue.bikesList.size() - 1);
	}

	public static void save(ArrayList<Bike> bikesList) throws IOException {
		try {
			int[] bikesIdList = new int[bikesList.size()];
			int index = 0;
			boolean isValid = true;
			String errorMessage = "Please follow the instruction below: "
					+ "\n" + "============================";

			for (int i = 0; i < bikesList.size(); i++) {
				bikesIdList[i] = bikesList.get(i).getBikeId();
			}

			if (FormBikeCatalogue.bikeIDTextField.getText().trim().equals("")) {
				errorMessage = errorMessage + "\n" + "Please enter the Bike ID";
				isValid = false;
			}

			if (FormBikeCatalogue.modelNameComboBox.getSelectedItem().equals(
					"Please select")) {
				errorMessage = errorMessage + "\n"
						+ "Please select the Model Name";
				isValid = false;
			}

			if (FormBikeCatalogue.descriptionTextField.getText().trim()
					.equals("")) {
				errorMessage = errorMessage + "\n"
						+ "Please enter the Description";
				isValid = false;
			}

			if (FormBikeCatalogue.yearComboBox.getSelectedItem().equals(
					"Please select")) {
				errorMessage = errorMessage + "\n"
						+ "Please select the Year bought";
				isValid = false;
			}

			if (FormBikeCatalogue.engineSpecificationsTextField.getText()
					.trim().equals("")) {
				errorMessage = errorMessage + "\n"
						+ "Please enter the Specifications";
				isValid = false;
			}

			if (FormBikeCatalogue.rentalCostTextField.getText().trim()
					.equals("")) {
				errorMessage = errorMessage + "\n"
						+ "Please enter the Rental Cost";
				isValid = false;
			}

			if (!Validation.isNumber(FormBikeCatalogue.bikeIDTextField
					.getText().trim())) {
				errorMessage = errorMessage + "\n"
						+ "Bike Id must be a positive number";
				isValid = false;
			} else if (!Validation.validateBikeID(Integer
					.parseInt(FormBikeCatalogue.bikeIDTextField.getText()
							.trim()))) {
				errorMessage = errorMessage + "\n"
						+ "Bike Id must be from 0001 to 9999";
				isValid = false;
			}

			if (!Validation.isDouble(FormBikeCatalogue.rentalCostTextField
					.getText().trim())) {
				errorMessage = errorMessage + "\n"
						+ "Rental Cost must be a number";
				isValid = false;
			}

			if (!isValid) {
				JOptionPane.showMessageDialog(null, errorMessage,
						FormBikeCatalogue.FORM_TITLE, 2);
			}

			if (isValid) {
				if (!Validation.notInBikeIdList(Integer
						.parseInt(FormBikeCatalogue.bikeIDTextField.getText()
								.trim()), bikesIdList)) {

					// Update an existed Bike
					// ======================

					if (JOptionPane
							.showConfirmDialog(
									null,
									"This Bike ID exists. Do you really want to change the details of this bike?",
									FormBikeCatalogue.FORM_TITLE,
									JOptionPane.YES_NO_OPTION) == 0) {

						// Get the index of the bikeId in the BikesIDlist
						for (int i = 0; i < bikesIdList.length; i++) {

							// If duplicate
							if (Integer
									.parseInt(FormBikeCatalogue.bikeIDTextField
											.getText().trim()) == bikesIdList[i]) {
								index = i;
							}
						}

						bikesList.get(index).setModelName(
								FormBikeCatalogue.modelNameComboBox
										.getSelectedItem().toString());
						bikesList.get(index).setDescription(
								FormBikeCatalogue.descriptionTextField
										.getText());
						bikesList.get(index).setEngineCapacity(
								FormBikeCatalogue.modelNameComboBox
										.getSelectedItem().toString());
						bikesList.get(index).setYear(
								Integer.parseInt(FormBikeCatalogue.yearComboBox
										.getSelectedItem().toString()));
						bikesList.get(index).removeSpecifications();
						// bikesList.get(index).setSpecifications(specifications)

						String specList = FormBikeCatalogue.engineSpecificationsTextField
								.getText();
						StringTokenizer tokenSpec = new StringTokenizer(
								specList, ",");
						ArrayList<BikeEngineSpecification> specShow = new ArrayList<BikeEngineSpecification>();
						while (tokenSpec.hasMoreElements()) {
							String specStr = tokenSpec.nextToken();
							BikeEngineSpecification spec = new BikeEngineSpecification(
									specStr);
							specShow.add(spec);
						}
						bikesList.get(index).setSpecifications(specShow);
						bikesList
								.get(index)
								.setRentalCost(
										Integer.parseInt(FormBikeCatalogue.yearComboBox
												.getSelectedItem().toString()),
										Integer.parseInt(FormBikeCatalogue.engineCapacityTextField
												.getText()),
										FormBikeCatalogue.modelNameComboBox
												.getSelectedItem().toString());

						saveToFile(bikesList);

					} else
						return;

				} else {

					// Add new bike
					// ============
					if (JOptionPane
							.showConfirmDialog(
									null,
									"This Bike ID does not exist. Do you want to save this new bike?",
									FormBikeCatalogue.FORM_TITLE,
									JOptionPane.YES_NO_OPTION) == 0) {

						Bike newBike = new Bike();

						newBike.setBikeId(Integer
								.parseInt(FormBikeCatalogue.bikeIDTextField
										.getText().trim()));
						newBike.setModelName(FormBikeCatalogue.modelNameComboBox
								.getSelectedItem().toString());
						newBike.setDescription(FormBikeCatalogue.descriptionTextField
								.getText());
						newBike.setEngineCapacity(FormBikeCatalogue.modelNameComboBox
								.getSelectedItem().toString());
						newBike.setYear(Integer
								.parseInt(FormBikeCatalogue.yearComboBox
										.getSelectedItem().toString()));
						String specifi = FormBikeCatalogue.engineSpecificationsTextField
								.getText();
						StringTokenizer tokenSpec = new StringTokenizer(
								specifi, ",");
						ArrayList<BikeEngineSpecification> specShow = new ArrayList<BikeEngineSpecification>();
						while (tokenSpec.hasMoreElements()) {
							String specStr = tokenSpec.nextToken();
							BikeEngineSpecification spec = new BikeEngineSpecification(
									specStr);
							specShow.add(spec);
						}
						newBike.setSpecifications(specShow);

						newBike.setRentalCost(
								Integer.parseInt(FormBikeCatalogue.yearComboBox
										.getSelectedItem().toString()),
								Integer.parseInt(FormBikeCatalogue.engineCapacityTextField
										.getText()),
								FormBikeCatalogue.modelNameComboBox
										.getSelectedItem().toString());

						bikesList.add(newBike);

						saveToFile(bikesList);
						System.out.println("Write Success");

					} else
						return;
				}
			}
		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			// Close the BufferedWriter
			try {

				if (bufferedWriter != null) {

					bufferedWriter.close();

				}

			} catch (IOException ex) {

			}
		}
	}

	public static void delete(ArrayList<Bike> bikesList) throws IOException {

		try {
			int index = -1;
			int[] bikesIdList = new int[bikesList.size()];
			boolean isValid = true;
			String errorMessage = "Please follow the instruction below: "
					+ "\n" + "============================";

			for (int i = 0; i < bikesList.size(); i++) {
				bikesIdList[i] = bikesList.get(i).getBikeId();
			}

			if (FormBikeCatalogue.bikeIDTextField.getText().trim().equals("")) {
				errorMessage = errorMessage + "\n" + "Please enter the Bike ID";
				isValid = false;
			} else if (!Validation.isNumber(FormBikeCatalogue.bikeIDTextField
					.getText().trim())) {
				errorMessage = errorMessage + "\n"
						+ "Bike Id must be a positive number";
				isValid = false;
			} else if (!Validation.validateBikeID(Integer
					.parseInt(FormBikeCatalogue.bikeIDTextField.getText()
							.trim()))) {
				errorMessage = errorMessage + "\n"
						+ "Bike Id must be from 0001 to 9999";
				isValid = false;
			} else if (Validation.notInBikeIdList(Integer
					.parseInt(FormBikeCatalogue.bikeIDTextField.getText()
							.trim()), bikesIdList)) {
				errorMessage = errorMessage + "\n"
						+ "This Bike ID is not in the Bike Catalogue" + "\n"
						+ "Please enter another Bike ID";
				isValid = false;
			}

			if (!isValid) {
				JOptionPane.showMessageDialog(null, errorMessage,
						FormBikeCatalogue.FORM_TITLE, 2);

			} else {
				if (JOptionPane
						.showConfirmDialog(null,
								"Do you really want to delete this Bike?",
								FormBikeCatalogue.FORM_TITLE,
								JOptionPane.YES_NO_OPTION) == 0) {

					int bikeID = Integer
							.parseInt(FormBikeCatalogue.bikeIDTextField
									.getText().trim());

					// Search the bikeId in the array list
					for (int i = 0; i < bikesIdList.length; i++) {

						// If duplicate
						if (bikeID == bikesIdList[i]) {
							index = i;
						}
					}

					bikesList.remove(index);

					saveToFile(bikesList);

					// Clear the form
					clear();

				} else
					return;
			}
		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			// Close the BufferedWriter
			try {

				if (bufferedWriter != null) {

					bufferedWriter.close();

				}

			} catch (IOException ex) {

			}

		}

	}

	
	public static void search(ArrayList<Bike> bikesList) {
		try {
			int index = -1;
			int[] bikesIdList = new int[bikesList.size()];
			boolean isValid = true;
			String errorMessage = "Please follow the instruction below: "
					+ "\n" + "============================";

			for (int i = 0; i < bikesList.size(); i++) {
				bikesIdList[i] = bikesList.get(i).getBikeId();
			}

			if (FormBikeCatalogue.bikeIDTextField.getText().trim().equals("")) {
				errorMessage = errorMessage + "\n" + "Please enter the Bike ID";
				isValid = false;
			} else if (!Validation.isNumber(FormBikeCatalogue.bikeIDTextField
					.getText().trim())) {
				errorMessage = errorMessage + "\n"
						+ "Bike Id must be a positive number";
				isValid = false;
			} else if (!Validation.validateBikeID(Integer
					.parseInt(FormBikeCatalogue.bikeIDTextField.getText()
							.trim()))) {
				errorMessage = errorMessage + "\n"
						+ "Bike Id must be from 0001 to 9999";
				isValid = false;
			} else if (Validation.notInBikeIdList(Integer
					.parseInt(FormBikeCatalogue.bikeIDTextField.getText()
							.trim()), bikesIdList)) {
				errorMessage = errorMessage + "\n"
						+ "This Bike ID is not in the Bike Catalogue" + "\n"
						+ "Please enter another Bike ID";
				isValid = false;
			}

			if (!isValid) {
				JOptionPane.showMessageDialog(null, errorMessage,
						FormBikeCatalogue.FORM_TITLE, 2);
			} else {
				int bikeID = Integer.parseInt(FormBikeCatalogue.bikeIDTextField
						.getText().trim());
				for (int i = 0; i < bikesIdList.length; i++) {
					if (bikesIdList[i] == bikeID) {
						index = i;
						break;
					}
				}
				
				FormBikeCatalogue.loadBike(index);
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	// ==============================================================

	public static void clear() {
		// Clear all the fields
		FormBikeCatalogue.bikeIDTextField.setText("");
		FormBikeCatalogue.modelNameComboBox.setSelectedIndex(0);
		FormBikeCatalogue.descriptionTextField.setText("");
		FormBikeCatalogue.engineCapacityTextField.setText("");
		FormBikeCatalogue.yearComboBox.setSelectedIndex(0);
		FormBikeCatalogue.engineSpecificationsTextField.setText("");
		FormBikeCatalogue.rentalCostTextField.setText("");

		// Set focus to the Bike ID field
		FormBikeCatalogue.bikeIDTextField.requestFocusInWindow();

	}

	public static void clearConfirmation() {

		if (FormBikeCatalogue.bikeIDTextField.getText().trim().equals("")
				&& FormBikeCatalogue.modelNameComboBox.getSelectedItem()
						.equals("Please select")
				&& FormBikeCatalogue.descriptionTextField.getText().trim()
						.equals("")
				&& FormBikeCatalogue.yearComboBox.getSelectedItem().equals(
						"Please select")
				&& FormBikeCatalogue.engineSpecificationsTextField.getText()
						.trim().equals("")
				&& FormBikeCatalogue.rentalCostTextField.getText().trim()
						.equals("")) {
			JOptionPane.showMessageDialog(null,
					"There is nothing to clear. Please enter the data.",
					FormBikeCatalogue.FORM_TITLE, 2);
		} else {
			if (JOptionPane.showConfirmDialog(null,
					"Do you really want to clear the form?",
					FormBikeCatalogue.FORM_TITLE, JOptionPane.YES_NO_OPTION) == 0) {
				clear();
			} else
				return;
		}

	}

	public static void exit() {
		if (JOptionPane.showConfirmDialog(null,
				"Do you really want to close the form?",
				FormBikeCatalogue.FORM_TITLE, JOptionPane.YES_NO_OPTION) == 0) {

			System.exit(0);
		} else
			return;

	}

	public static void generateModelReport(ArrayList<Bike> bikes) {
		FormReportBikeModelName modelReport = new FormReportBikeModelName(bikes);
		modelReport.setVisible(true);

	}

	public static void generateSpecificationReport(ArrayList<Bike> bikes) {
		FormEngineSpecification engineSpecificationReport = new FormEngineSpecification(
				bikes);
		engineSpecificationReport.setVisible(true);

	}

	public static void generateModelSpecificationReport(ArrayList<Bike> bikes) {
		FormModelAndSpecification modelSpecificationReport = new FormModelAndSpecification(
				bikes);
		modelSpecificationReport.setVisible(true);

	}

	public static void openAboutForm(ArrayList<Bike> bikeList) {
		FormAbout formAbout = new FormAbout(bikeList);
		formAbout.setVisible(true);
	}

	public static void backToMainForm(ArrayList<Bike> bikeList) {

		FormBikeCatalogue mainform = new FormBikeCatalogue();
		try {
			mainform.run();
		} catch (Exception e) {

			e.printStackTrace();
		}
		mainform.setVisible(true);

	}

	private static void saveToFile(ArrayList<Bike> bikesList)
			throws IOException {
		bufferedWriter = new BufferedWriter(new FileWriter(
				FormBikeCatalogue.DATA_FILE_NAME, false));

		// Use BufferWriter to write all details into text file
		// Create new text file and delete the old one
		for (int i = 0; i < bikesList.size(); i++) {
			String specificationStr = "";
			ArrayList<BikeEngineSpecification> specList2 = bikesList.get(i)
					.getSpecifications();
			for (int j = 0; j < specList2.size(); j++) {
				if (j < specList2.size() - 1)
					specificationStr += specList2.get(j).getSpecification()
							+ ",";
				else
					specificationStr += specList2.get(j).getSpecification();
			}

			bufferedWriter.write(bikesList.get(i).getBikeId() + ";"
					+ bikesList.get(i).getModelName() + ";"
					+ bikesList.get(i).getDescription() + ";"
					+ bikesList.get(i).getEngineCapacity() + ";"
					+ bikesList.get(i).getYear() + ";" + specificationStr + ";"
					+ bikesList.get(i).getRentalCost() + ";");

			bufferedWriter.newLine();

		}
	}
}
